<?php
/**
 * Created by PhpStorm.
 * User: FDG296
 * Date: 2017/8/1
 * Time: 16:02
 */
namespace backend\controllers;

use backend\models\GoodsTag;
use backend\models\GoodsTagGroup;
use Yii;
use yii\web\AdminController;
use backend\models\GoodsCategory;
use backend\models\GoodsCateRelation;

class GoodsTagController extends AdminController{
    public $layout = false;
    //业务关键字
    public $service = 'GoodsTag';

    /**
     * 导航相关修改时清空导航redis缓存
     * action 方法名
     */
    public function beforeAction($action){

        $currentaction = $action->id;

        $novalidactions = ['add-tag','update-tag','disable-tag','enable-tag','add-tag-group','update-tag-group',
        'disable-group','enable-group'];

        if(in_array($currentaction,$novalidactions)){

            \common\helps\tools::delWebNavRedis();

        }
        parent::beforeAction($action);

        return true;
    }

    /**
     * 商品品类列表
     */
    public function actionGetGoodsTag(){
        $data = Yii::$app->request->post();
        $count = 0;
        $list = array();
        if(!empty($data['tag_group_id'])){

            if(!empty($data['tag_name'])){
                $condition = "tag_group_id = ".$data['tag_group_id']." and tag_name like '%".$data['tag_name']."%'";
                $where = array();
            }else{
                $condition = "tag_group_id=:tag_group_id";
                $where = array(':tag_group_id'=>$data['tag_group_id']);
            }
            $query = GoodsTag::find()->where($condition,$where);
            $count = $query->count();
            $sort_string = empty($data['columns'][$data['order'][0]['column']]['data']) ? 'id' : $data['columns'][$data['order'][0]['column']]['data'];

            $list = $query->offset($data['start'])->limit($data['length'])
                ->orderBy(array("$sort_string"=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC))->asArray()->all();
            if(empty($list)){
                $list = array();
            }
        }
        //相关参数   http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;

        return \yii\helpers\Json::encode($result);
    }

    /**
     * 新增商品品类
     */
    public function actionAddTag(){
        $model = new GoodsTag();

        //获取品类组
        $tag_group = GoodsTagGroup::find()->select('id,tag_group_name,tag_group_alias')->asArray()->all();

        $tag_group_list = array();
        foreach($tag_group as $value){
            $tag_group_list[$value['id']]['tag_group_name'] = $value['tag_group_name'];
            $tag_group_list[$value['id']]['tag_group_alias'] = $value['tag_group_alias'];
        }

        $data = Yii::$app->request->post();
        $data_now['tag_group_id'] = $data['tag_group_id'];
        $data_now['tag_group_name'] = $tag_group_list[$data['tag_group_id']]['tag_group_name'];
        $data_now['tag_group_alias'] = $tag_group_list[$data['tag_group_id']]['tag_group_alias'];
        if(!empty($data['add_tag_name'])){
            $tag_name_list = $data['add_tag_name'];
            $tag_alias_list = $data['add_tag_alias'];
            $tag_sort_list = $data['add_tag_sort'];

            //删除数组中空的元素
            foreach($tag_name_list as $value){
                if(empty($value)){
                    $num = array_search($value,$tag_name_list);
                    array_splice($tag_name_list,$num,1);
                    array_splice($tag_alias_list,$num,1);
                    array_splice($tag_sort_list,$num,1);
                }
            }

            //去重
            $tag_name = array_unique($tag_name_list);
        }else{
            $this->retJson('请输入品类名称',500);
            return false;
        }
        $list = array();
        foreach($tag_name as $key=>$value){
            $list[] = [trim($value),trim($tag_alias_list[$key]),$data_now['tag_group_id'],$data_now['tag_group_name'],$data_now['tag_group_alias'],
                $tag_sort_list[$key],1,$model->getCreator(),date('Y-m-d H:i:s',time())];
        }
        $fields = ['tag_name','tag_alias','tag_group_id','tag_group_name','tag_group_alias','sort','use_flg','creator','create_time'];
        $res = Yii::$app->db->createCommand()->batchInsert('j_goods_tag',$fields,$list)->execute();
        if($res > 0){
            $this->saveLog($this->service,'商品品类新增','ADD','');
            $this->retJson('添加成功',200);
        }else{
            $this->retJson('操作失败',500);
        }
    }

    /**
     * 获取商品品类详情(编辑用)
     */
    public function actionGetOneTag(){
        $data = Yii::$app->request->post();

        $result = GoodsTag::find()->where("id=:id",array(':id'=>$data['id']))->asArray()->one();
        return \yii\helpers\Json::encode($result);
    }

    /**
     * 编辑商品品类
     */
    public function actionUpdateTag(){
        $model = new GoodsTag();

        //获取品类组
        $tag_group = GoodsTagGroup::find()->select('id,tag_group_name,tag_group_alias')->asArray()->all();

        $tag_group_list = array();
        foreach($tag_group as $value){
            $tag_group_list[$value['id']]['tag_group_name'] = $value['tag_group_name'];
            $tag_group_list[$value['id']]['tag_group_alias'] = $value['tag_group_alias'];
        }

        $data = Yii::$app->request->post();

        $data_now['tag_name'] = trim($data['tag_name']);
        $data_now['tag_alias'] = trim($data['tag_alias']);
        $data_now['tag_group_id'] = $data['tag_group_id'];
        $data_now['edit_time'] = date('Y-m-d H:i:s',time());
        $data_now['editor'] = $model->getCreator();
        $data_now['use_flg'] = $data['use_flg'];
        $data_now['sort'] = empty($data['sort']) ? 1 : $data['sort'];;
        $data_now['tag_group_name'] = $tag_group_list[$data['tag_group_id']]['tag_group_name'];
        $data_now['tag_group_alias'] = $tag_group_list[$data['tag_group_id']]['tag_group_alias'];
        $res = $model::updateAll($data_now, "id=:id",array(':id'=>$data['tag_id']));
        if($res > 0){
            $this->saveLog($this->service,'商品品类编辑','MOD',\yii\helpers\Json::encode($data_now));
            $this->retJson('编辑成功',200);
        }else{
            $this->retJson('操作失败',500);
        }
    }

    /**
     * 禁用品类
     */
    public function actionDisableTag(){
        $model = new GoodsTag();
        $data = Yii::$app->request->post();
        $find_cate_relation = GoodsCateRelation::find()->select('category_id')->where(['tag_id'=>$data['id'],'use_flg'=>GoodsCateRelation::STATUS_ENABLE])->asArray()->all();
        if (count($find_cate_relation) > 0){
            $category_ids = array_column($find_cate_relation, 'category_id');
            $category_name = GoodsCategory::find()->select('category_name')->where(['id'=>$category_ids])->asArray()->all();
            if (count($category_name) > 0){
                $category_name = array_column($category_name, 'category_name');
                $this->retJson('在【'.implode('、', $category_name).'】分类下，已经使用，无法禁用。未使用可直接去除勾选',500);
            }
        }
        $mod_data['use_flg'] = 0;
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());

        $res = $model::updateAll($mod_data, "id=:id",array(':id'=>$data['id']));

        if($res > 0){
            $this->saveLog($this->service,'品类禁用','USEFLG0', '品类ID：' . $data['id']);
            $this->retJson('禁用成功',200);
        }else{
            $this->retJson('禁用失败',500);
        }
    }

    /**
     * 启用品类
     */
    public function actionEnableTag(){
        $model = new GoodsTag();
        $data = Yii::$app->request->post();

        $mod_data['use_flg'] = 1;
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());

        $res = $model::updateAll($mod_data, "id=:id",array(':id'=>$data['id']));

        if($res > 0){
            $this->saveLog($this->service,'品类启用','USEFLG1', '品类ID：' . $data['id']);
            $this->retJson('启用成功',200);
        }else{
            $this->retJson('启用失败',500);
        }
    }

    /**
     * 品类组
     */
    public function actionIndex(){

        //编辑用
        $list = GoodsTagGroup::find()->asArray()->all();

        //新增用
        $list_group = GoodsTagGroup::find()->where(array('use_flg'=>1))->asArray()->all();
        $this->saveLog($this->service,'商品品类组查询','VIEW', '');
        return $this->render('index',['list'=>$list,'list_group'=>$list_group]);
    }

    /**
     * 商品品类组列表
     */
    public function actionGetTagGroupList(){
        $data = Yii::$app->request->post();
        $condition = array();
        if(!empty($data['tag_group_name'])){
            $condition = ['like', 'tag_group_name', $data['tag_group_name']];
        }
        $query = GoodsTagGroup::find()->where($condition);
        $count = $query->count();
        $sort_string = empty($data['columns'][$data['order'][0]['column']]['data']) ? 'id' : $data['columns'][$data['order'][0]['column']]['data'];
        $list = $query->offset($data['start'])->limit($data['length'])
            ->orderBy(array("$sort_string"=>$data['order'][0]['dir'] == 'asc' ? SORT_ASC : SORT_DESC))->all();
        if(empty($list)){
            $list = array();
        }

        //相关参数   http://datatables.club/manual/server-side.html
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        return \yii\helpers\Json::encode($result);
    }

    /**
     * 新增商品品类组
     */
    public function actionAddTagGroup(){
        $model = new GoodsTagGroup();
        $data = Yii::$app->request->post();

        $data_now['tag_group_name'] = trim($data['tag_group_name']);
        $data_now['tag_group_alias'] = trim($data['tag_group_alias']);
        $data_now['create_time'] = date('Y-m-d H:i:s',time());
        $data_now['creator'] = $model->getCreator();
        $data_now['use_flg'] = $data['use_flg'];
        $data_now['sort'] = empty($data['sort']) ? 1 : $data['sort'];;

        $res = Yii::$app->db->createCommand()->insert('j_goods_tag_group',$data_now)->execute();
        if($res > 0){
            $this->saveLog($this->service,'商品品类新增','ADD', '品类组名称：' . $data_now['tag_group_name'] . "\r\n" . \yii\helpers\Json::encode($data_now));
            $this->retJson('品类组增加成功',200);
        }else{
            $this->retJson('品类组增加失败',500);
        }
    }

    /**
     * 获取品类组详情
     */
    public function actionGetOneTagGroup(){
        $data = Yii::$app->request->post();

        $result = GoodsTagGroup::findOne(array('id'=>$data['id']));
        return \yii\helpers\Json::encode($result);
    }

    /**
     * 修改商品品类组
     */
    public function actionUpdateTagGroup(){
        $model = new GoodsTagGroup();
        $data = Yii::$app->request->post();

        $data_now['tag_group_name'] = $data['tag_group_name'];
        $data_now['tag_group_alias'] = trim($data['tag_group_alias']);
        $data_now['edit_time'] = date('Y-m-d H:i:s',time());
        $data_now['editor'] = $model->getCreator();
        $data_now['use_flg'] = $data['use_flg'];
        $data_now['sort'] = empty($data['sort']) ? 1 : $data['sort'];;

        $res = $model::updateAll($data_now, "id=:id",array(':id'=>$data['id']));
        if($res > 0){
            $this->saveLog($this->service,'品类组修改','MOD', '品类组名称：' . $data_now['tag_group_name'] . "\r\n" . \yii\helpers\Json::encode($data_now));
            $this->retJson('品类组修改成功',200);
        }else{
            $this->retJson('品类组修改失败',500);
        }
    }

    /**
     * 禁用品类组
     */
    public function actionDisableGroup(){
        $model = new GoodsTagGroup();
        $data = Yii::$app->request->post();

        $mod_data['use_flg'] = 0;
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());
        $goods_category = GoodsCateRelation::find()->select('category_id')->where('tag_group_id=:tag_group_id',[':tag_group_id'=>$data['id']])->asArray()->all();
        if (count($goods_category) > 0){
            $category_ids = array_column($goods_category, 'category_id');
            $category = GoodsCategory::find()->select('category_name')->where(['id'=>$category_ids])->asArray()->all();
            if (count($category) > 0){
                $category_name = array_column($category, 'category_name');
                $this->retJson('在【'.implode('、', $category_name).'】分类下，已经使用，无法禁用',500);
            }
        }
        $res = $model::updateAll($mod_data, "id=:id",array(':id'=>$data['id']));

        if($res > 0){
            $this->saveLog($this->service,'品类组禁用','USEFLG0', '品类组ID：' . $data['id']);
            $this->retJson('禁用成功',200);
        }else{
            $this->retJson('禁用失败',500);
        }
    }

    /**
     * 启用品类组
     */
    public function actionEnableGroup(){
        $model = new GoodsTagGroup();
        $data = Yii::$app->request->post();

        $mod_data['use_flg'] = 1;
        $mod_data['editor'] = $model->getCreator();
        $mod_data['edit_time'] = date('Y-m-d H:i:s',time());

        $res = $model::updateAll($mod_data, "id=:id",array(':id'=>$data['id']));

        if($res > 0){
            $this->saveLog($this->service,'品类组启用','USEFLG1', '品类组ID：' . $data['id']);
            $this->retJson('启用成功',200);
        }else{
            $this->retJson('启用失败',500);
        }
    }
}